useReducer使用 |
您所在的位置:网站首页 › usereducer usestate › useReducer使用 |
熟悉 redux 的同学都知道,在 redux 中,状态并不直接更改,而是通过发起 action 给状态管理器,收到 action 后,使用 reducer 计算出新的状态,即(state, action) => newState。 useReducer()也是一样的,const [state,dispatch] = useReducer(reducer, initialState),它接收一个形如(state, action) => newState的 reducer,并返回当前 state 以及发起 action 的 dispath 方法。 以下是用useReducer实现了一个基数Demo: import { useReducer } from "react"; const initState = { num: 0, }; interface initStateType { num: number; } interface actionType { type: string; } const numReducer = (state: initStateType, action: actionType) => { switch (action.type) { case "add": return { ...state, num: state.num + 1 }; case "reduce": return { ...state, num: state.num - 1 }; default: return state; } }; const Example = () => { const [state, dispatch] = useReducer(numReducer, initState); return ( 数量: {state.num} dispatch({ type: "reduce" })}>减少 dispatch({ type: "add" })}>增加 ); }; export default Example;使用方法和redux几乎一模一样。 效果图 |
CopyRight 2018-2019 办公设备维修网 版权所有 豫ICP备15022753号-3 |